# Create your views here.
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

from user.models import User


# 注册账号
@csrf_exempt
def register(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        email = request.POST.get('email')
        user = User.objects.filter(username=username).first()
        if user is None:
            User.objects.create(username=username, password=password, email=email)
            return JsonResponse({'code': 200, 'msg': '注册成功',
                                 'data': {'username': username, 'password': password, 'email': email}})
        else:
            return JsonResponse({'code': 400, 'msg': '用户名已存在'})
    else:
        return JsonResponse({'code': 400, 'msg': '请求方式错误'})
    pass


# 登录
@csrf_exempt
def login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = User.objects.filter(username=username, password=password).first()
        if user is None:
            return JsonResponse({'code': 400, 'msg': '用户名或密码错误'})
        else:
            return JsonResponse({'code': 200, 'msg': '登录成功',
                                 'data': {'username': username, 'password': password, 'email': user.email}})
    else:
        return JsonResponse({'code': 400, 'msg': '请求方式错误'})
    pass


# 登出
def logout():
    pass


# 查看用户信息
@csrf_exempt
def user_info(request):
    if request.method == 'GET':
        user_id = request.GET.get('user_id')
        user = User.objects.filter(user_id=user_id).first()
        if user is None:
            return JsonResponse({'code': 400, 'msg': '用户不存在'})
        else:
            return JsonResponse({'code': 200, 'msg': '查询成功',
                                 'data': {'username': user.username, 'password': user.password, 'email': user.email}})
    else:
        return JsonResponse({'code': 400, 'msg': '请求方式错误'})
    pass
